<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>调用摄像头</title>
</head>
<body>
<h2>浏览器调用摄像头, 需要用户同意并授权</h2>
<hr>
<div style="text-align:center;">
    <canvas id="c" width="640" height="480"></canvas>
</div>

<script type="text/javascript">
    function doTestCamera() {
        let c = document.querySelector("#c");
        //设置Canvas大小
        c.width = 1280;
        c.height = 720;
        let ctx = c.getContext("2d");

        let width = c.width;

        // 创建video标签
        let video = document.createElement("video");
        video.autoplay = true;
        
        // 获得摄像头
        let cameraObj = navigator.mediaDevices.getUserMedia({ video: true });
        console.log('camera:', cameraObj);
        cameraObj.then((stream) => {
            // 将视频流同步到html中的video标签
            video.srcObject = stream;
            // 视频加载成功后播放
            video.onloadeddata = function () {
                console.log(video);
                // 通知视频可以播放流中的内容了,触发onplay事件,
                // 视频一边在内存中播放,一边将其绘制到Canvas中
                video.play();
            }
        }).catch((error) => {
            alert(error);
        });
    
        // 绘制视频到Canvas
        video.oncanplay = function () {
            (function playDraw() {
                // 绘制视频
                ctx.drawImage(video, 0, 0);
                requestAnimationFrame(playDraw);
            })();
        };
    }
    window.addEventListener('load', doTestCamera);
</script>
</body>
</html>